package com.lollipop.programming.thread.sequential;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Author Lollipop
 * @Date 2025/7/28 16:37
 * @Description 多线程顺序执行 - 线程CyclicBarrier Demo
 * @Version 1.0
 */
@Slf4j
public class ThreadCyclicBarrier {
    public static void main(String[] args) {
        CyclicBarrier barrierAB = new CyclicBarrier(1);
        CyclicBarrier barrierBC = new CyclicBarrier(1);

        Thread threadA = new Thread(() -> {
            log.info("任务A开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("任务A执行异常：{}", e.getMessage());
            }
            log.info("任务A执行完成");
            try {
                barrierAB.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                log.error("任务A等待异常：{}", e.getMessage());
            }
        });

        Thread threadB = new Thread(() -> {
            try {
                barrierAB.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                log.error("任务B等待异常：{}", e.getMessage());
            }
            log.info("任务B开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("任务B执行异常：{}", e.getMessage());
            }
            log.info("任务B执行完成");
            try {
                barrierBC.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });

        Thread threadC = new Thread(() -> {
            try {
                barrierBC.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
            log.info("任务C开始执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("任务C执行完成");
        });

        threadA.start();
        threadB.start();
        threadC.start();
    }
}
